package com.classload.controller;


import com.classload.domain.Order;
import com.classload.domain.Product;
import com.classload.service.OrderService;
import com.classload.service.ProductService;
import com.classload.service.impl.OrderServiceImpl2;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class OrderController2 {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    OrderService orderService;

    @Autowired
    ProductService productService;

    @Autowired
    OrderServiceImpl2 orderServiceImpl2;
    @Autowired
    RocketMQTemplate rocketMQTemplate;
    @RequestMapping("/order/message1")
    public String message1() {
        return orderServiceImpl2.testLink();
    }

    int i = 0;

    @RequestMapping("/order/message2")
    public String message2() {
        //模拟异常比例超过25%
        i++;
        if (i % 3 == 0) {
            throw new RuntimeException();
        }


        return "1";

//        return orderServiceImpl2.testLink();
    }


    //    下游应用 资源名称 testLink


    @RequestMapping("/order/product/{pid}")
    public Order createOrder(@PathVariable("pid") Integer pid) throws InterruptedException {


        //模拟feign调用失败  调用备用类
        Product product = productService.findByPid(pid);


        if (product.getPid() == -500) {
            Order order = new Order();
            order.setPname("下单失败");
            return order;
        }


        Thread.sleep(2000);
        //创建订单
        Order order = new Order();
        order.setUid(1);
        order.setPid(pid);
        order.setUsername("刘丹");
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        orderService.createOrder(order);
        //发送消息
        rocketMQTemplate.convertAndSend("order-topic",order);
        return order;
    }
}
